//
//  StartupItemController.m
//  Isolator
//
//  Created by Ben Willmore on 12/02/2007.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "StartupItemController.h"

@implementation StartupItemController

-(id) init
{
	[super init];
	
	return self;
}

-(BOOL) enabled
{
	OSStatus err;
	NSArray* itemArray = NULL;
	
	err = LIAECopyLoginItems((CFArrayRef*)&itemArray);
	
	if (err != noErr)
		return NO;
	
	BOOL found = NO;
	
	NSArray* pathComponents = [[[NSBundle mainBundle] bundlePath] pathComponents];
	NSString* name = [pathComponents objectAtIndex:[pathComponents count]-1];
	NSString* nameComparison = [[@"*" stringByAppendingString:name] stringByAppendingString:@"*"];

	NSEnumerator* enumerator = [itemArray objectEnumerator];
	NSDictionary* item;
		
	while( item = [enumerator nextObject] ) {
		if ([[[item objectForKey:@"URL"] absoluteString] isLike:nameComparison])
			found = YES;
	}

	[itemArray release]; // added by BW
	
	return found;
}

-(void) setEnabled:(BOOL)value
{
	if ([self enabled])
		[self removeStartupItem];
	
	if (value)
		[self addStartupItem];
}


-(void) removeStartupItem
{
	OSStatus err;
	NSArray* itemArray = NULL;
		
	err = LIAECopyLoginItems((CFArrayRef*)&itemArray);
	
	if (err != noErr)
		return;
	
	NSArray* pathComponents = [[[NSBundle mainBundle] bundlePath] pathComponents];
	NSString* name = [pathComponents objectAtIndex:[pathComponents count]-1];
	NSString* nameComparison = [[@"*" stringByAppendingString:name] stringByAppendingString:@"*"];

	NSEnumerator* enumerator = [itemArray objectEnumerator];
	NSDictionary* item;

	CFIndex idx = 0;
	BOOL removed = NO;
	while( (item = [enumerator nextObject]) && (!removed) ) {
		if ([[[item objectForKey:@"URL"] absoluteString] isLike:nameComparison]){
			LIAERemove(idx);
			removed = YES;
		}
		idx = idx + 1;
	}
}

-(void) addStartupItem
{
	LIAEAddURLAtEnd((CFURLRef)[NSURL URLWithString:[[NSBundle mainBundle] bundlePath]],NO);
}
		
@end
